#!/bin/bash
ROOT=$(/Data/apps/php/bin/php -r "echo realpath('`dirname $0`/../');")
createlink() {
    echo "    create link $2 => $1"
    rm -f $2
    ln -s $1 $2
}
myecho() {
    echo -en $"\\033[0;32m $1 \\033[0;39m\n"
}

rm -f /Data/apps/nginx/conf/include/*.conf

bash $ROOT/services/init_env.sh

#部署前端应用
PHP_DIR=$HOME/system/php
APP_DIR=$HOME/system/webapps


rm -Rf $APP_DIR
mkdir -p $APP_DIR

build_webapp() {
    APP_ROOT=$APP_DIR/$1
    APP_NAME=$1


    myecho "开始创建$APP_NAME系统运行环境..."

    if [ -f $APP_ROOT/config/server_template.php ]; then
        myecho "   创建系统配置文件 => $APP_ROOT/config/config.php"
        rm $APP_ROOT/config/config.php
        cat $APP_ROOT/config/server_template.php > $APP_ROOT/config/config.php
    fi

    if [ -f $APP_ROOT/config/nginx/template.conf ]; then
        myecho "   创建nginx配置文件 => /Data/apps/nginx/conf/include/9.dev.`echo $APP_NAME | sed -e "s|/|-|g"`.conf"
        createlink $APP_ROOT/config/nginx/template.conf /Data/apps/nginx/conf/include/2.dev.`echo $APP_NAME | sed -e "s|/|-|g"`.web.conf
    fi

    myecho "   创建assembly.php"
    /Data/apps/php/bin/php $APP_ROOT/project/build.php $PHP_DIR
    if [ -f $APP_ROOT/project/init_env.sh ]; then
        myecho "   执行$APP_NAME系统自定义初始化脚本 => $APP_ROOT/project/init_env.sh"
        bash $APP_ROOT/project/init_env.sh
    fi

    if [ ! -d $HOME/logs/webapps/$APP_NAME ]; then
        myecho "   创建webapps/$APP_NAME日志目录 => $HOME/logs/webapps/$APP_NAME"
        mkdir -p $HOME/logs/webapps/$APP_NAME
    fi 
}

WEB_APPS="wwwfront gamefront wenfront"
for WEB_APP in $WEB_APPS; do
    myecho "部署$WEB_APP..."

    createlink $ROOT/$WEB_APP $APP_DIR/$WEB_APP

    build_webapp $WEB_APP

done


#部署-初始化
mkdir -p /Data/cache

#部署img
myecho "部署img"
#createlink $ROOT/services/tu/config/nginx/hdfimg.conf /Data/apps/nginx/conf/include/0.dev.hdfimg.web.conf

